package com.sysu.ooad.dao.impl;

import java.util.List;

import org.hibernate.Session;
import org.springframework.stereotype.Component;

import com.sysu.ooad.dao.CommonDao;
import com.sysu.ooad.dao.GroupDao;
import com.sysu.ooad.entity.Course;
import com.sysu.ooad.entity.Group;

@Component("groupDao")
public class GroupDaoImpl extends CommonDao implements GroupDao{
	
	public void add(Group group) {
		hibernateTemplate.save(group);
	}

	public void delete(Group group) {
		Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
		session.clear();
		hibernateTemplate.delete(group);
	}

	public int findCountOfMembers(Group group) {
		@SuppressWarnings("rawtypes")
		List list = hibernateTemplate.find("select count(s) from Student s where s.group = ?)", new Object[]{group});
		return (Integer)list.get(0);
	}

	@SuppressWarnings("unchecked")
	public List<Group> findByCourse(Course c) {
		List<Group> groups = (List<Group>) hibernateTemplate.find("select distinct g from Group g join g.students where g.course = ?", new Object[]{c});
		return groups;
	}

	public Group getById(Integer id) {
		Group group = (Group)hibernateTemplate.get(Group.class, id);
//		group.getStudents();
		return group;
	}

	public void update(Group g) {
		hibernateTemplate.update(g);
	}
	
	public void merge(Group g) {
		hibernateTemplate.merge(g);
	}
}
